package com.ruike.alisurface.utils;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 日志上传工具类
 */
public class AlogHttpUtils {

    public static List<File> list = new ArrayList<>();
    public static int i = 0;
    public static String path = Environment.getExternalStorageDirectory().getAbsolutePath()
            + File.separator + "Alogs" + File.separator + BuildConfig.APPLICATION_ID;

    public static void upodataLog(String begin, String end) {
        File file = new File(path);
        File[] files = file.listFiles();// 读取
        getFileNameLog(files, begin, end);
    }

    private static void getFileNameLog(File[] files, String begin, String end) {
        if (files != null) {// 先判断目录是否为空，否则会报空指针
            L.i("开始获取上传文件");
            HashMap<String, File> map = new HashMap<>();
            for (File file : files) {
                //获取log日志中的文件名
                if (file.isFile()) {
                    String fileName = file.getName();
                    String timename = fileName.substring(0, fileName.lastIndexOf("."));
                    if (!begin.isEmpty() && !end.isEmpty()) {
                        L.i(" Nametime：" + dateToTimestamp(begin) + "---" + dateToTimestamp(timename) + "---" + dateToTimestamp(end));
                        if (dateToTimestamp(begin) <= dateToTimestamp(timename) && dateToTimestamp(end) >= dateToTimestamp(timename)) {
                            String filesname = path + File.separator + fileName;
                            uploadFile(Constant.HttpUrl.url_log + "?mchid=" + ShareUtils.getInstance().getString(ShareKey.MCH_ID),
                                    filesname);
//                        map.put("name", new File(filesname));
                            L.i("有日期getFileNameLog: 日志名称：" + fileName);
                        }
                    } else {
                        String filesname = path + File.separator + fileName;
                        uploadFile(Constant.HttpUrl.url_log + "?mchid=" + ShareUtils.getInstance().getString(ShareKey.MCH_ID),
                                filesname);
                        L.i("无日期getFileNameLog: 日志名称：" + fileName);
//                    map.put("name", new File(filesname));
                    }
                }
            }
//            sendFiles(context, map);
        }
    }

    /*
     * 将时间转换为时间戳
     */
    public static long dateToTimestamp(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = simpleDateFormat.parse(time);
            long ts = date.getTime() / 1000;
            return ts;
        } catch (ParseException e) {
            return 0;
        }
    }

    /*
     * 将时间戳转换为时间
     */
    public static String stampToDate(long s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(s);
        res = simpleDateFormat.format(date);
        return res;
    }


    /**
     * fileName 文件名(不带后缀)
     * filePath 文件的本地路径 (xxx / xx / test.jpg)
     */

    public static void uploadFile(String strServerUrl, String strFile) {
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        try {
            URL url = new URL(strServerUrl);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            /* 允许Input、Output，不使用Cache */
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            /* 设置传送的method=POST */
            con.setRequestMethod("POST");
            /* setRequestProperty */
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            con.setConnectTimeout(5 * 1000);
            con.setChunkedStreamingMode(0); // 设置该选项，则不使用HttpURLConnection的缓存机制，直接将流提交到服务器上 防止日志太大导致OOM
            String strFileName = strFile.substring(strFile.lastIndexOf("/") + 1);
            /* 设置DataOutputStream */
            DataOutputStream ds =
                    new DataOutputStream(con.getOutputStream());
            ds.writeBytes(twoHyphens + boundary + end);
            ds.writeBytes("Content-Disposition: form-data; " +
                    "name=\"file1\";filename=\"" +
                    strFileName + "\"" + end);
            ds.writeBytes(end);
            /* 取得文件的FileInputStream */
            FileInputStream fStream = new FileInputStream(strFile);
            /* 设置每次写入1024bytes */
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int length = -1;
            /* 从文件读取数据至缓冲区 */
            while ((length = fStream.read(buffer)) != -1) {
                /* 将资料写入DataOutputStream中 */
                ds.write(buffer, 0, length);
             }
            ds.writeBytes(end);
            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            /* close streams */
            L.i("tjf==" + ds.size());
            fStream.close();
            ds.flush();
            if (con.getResponseCode() == 200) {
                InputStream input = con.getInputStream();
                int ss;
                byte[] buffer1 = new byte[1024];
                StringBuilder builder = new StringBuilder();
                while ((ss = input.read(buffer1)) != -1) {
//                        sb1.append((char)ss);
                    builder.append(new String(buffer1, 0, ss, "UTF-8"));
                }
                L.i("tjf" + "响应成功==" + builder.toString());
            }
            /* 取得Response内容 */
            InputStream is = con.getInputStream();
            int ch;
            StringBuffer b = new StringBuffer();
            while ((ch = is.read()) != -1) {
                b.append((char) ch);
            }
            L.i("tjf" + b.toString());
            /* 关闭DataOutputStream */
            ds.close();

            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
